<template>
  <div class="pie-charts-container mt10">
    <div
      id="chart1"
      class="pie-chart-item"
    />
    <div
      id="chart2"
      class="pie-chart-item"
    />
    <div
      id="chart3"
      class="pie-chart-item"
    />
    <div
      id="chart4"
      class="pie-chart-item"
    />
  </div>
</template>
<script setup>
import * as echarts from 'echarts'
import { inject, onMounted, watch } from 'vue'
import { getPieChartData } from '@/apis/netflow'
import { useRoute } from 'vue-router'

const { timeRange } = inject('timeRange')

watch(timeRange, () => {
  init()
})
const route = useRoute()
const chartList = []
const createOption = (title, data) => {
  return {
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '流量',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}
const init = () => {
  const params = {
    ...route.query
  }
  if (timeRange.value.length === 2) {
    params.startDate = timeRange.value[0]
    params.endDate = timeRange.value[1]
  }
  getPieChartData(params).then(res => {
    if (res) {
      const titleList = [
        {
          title: '网站名称分布',
          key: 'site'
        },
        {
          title: '操作系统',
          key: 'os'
        },
        {
          title: '浏览器',
          key: 'browser'
        },
        {
          title: '采集省份排名',
          key: 'province'
        }
      ]
      titleList.forEach((val, index) => {
        let data = []
        if (res?.[val.key]) {
          data = res[val.key].map(item => {
            return {
              value: item.value,
              name: item.key
            }
          })
        }
        if (chartList[index]) {
          chartList[index].setOption(createOption(val.title, data))
          return
        }
        const chart = echarts.init(document.getElementById(`chart${index + 1}`))
        chart.setOption(createOption(val.title, data))
        chartList.push(chart)
      })
    }
  })
}
onMounted(() => {
  init()
})
</script>
<style lang="scss" scoped>
.pie-charts-container {
  display: flex;
  .pie-chart-item {
    background-color: #fff;
    flex: 1;
    height: 100%;
    height: 300px;
    &:not(:last-child) {
      margin-right: 10px;
    }
  }
}
</style>
